package com.sh15tech.mp.weixin.scan;

import com.sh15tech.mp.weixin.PropKey;
import com.sh15tech.mp.weixin.SysConfig;
import com.sh15tech.mp.weixin.common.Tool;
import com.sh15tech.mp.weixin.common.WxStore;
import com.sh15tech.mp.weixin.modal.WxCar;
import com.sh15tech.mp.weixin.modal.WxMessage;
import com.sh15tech.mp.weixin.modal.WxQRcode;
import com.sh15tech.mp.weixin.secure.WXBizMsgCrypt;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.util.Date;

@Controller
public class WxHandler {

	private Logger log = LogManager.getLogger(getClass());
	
	/**
	 * 接受微信服务器的消息
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/main_control", headers = {}, method = { RequestMethod.POST,RequestMethod.GET })
	@ResponseBody
	public String mainControl(HttpServletRequest request, HttpServletResponse response) {

		try {
//			BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
//	    	StringBuilder sb = new StringBuilder();
//	    	String line = null;
//	    	while((line=reader.readLine()) != null){
//	    		sb.append(line + "\n");
//	    	}
//	    	String s = sb.toString();
//	    	log.info("receive msg from wx server : "+s);
	    	// TODO

			WXBizMsgCrypt pc = new WXBizMsgCrypt(SysConfig.get(PropKey.CRYPT_TOKEN), SysConfig.get(PropKey.CRYPT_KEY), SysConfig.get(PropKey.APP_ID));
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
//			StringReader sr = new StringReader(s);
//			InputSource is = new InputSource(sr);
			Document document = db.parse(request.getInputStream());
			Element root = document.getDocumentElement();
			NodeList nodelist1 = root.getElementsByTagName("Encrypt");
			String encrypt = nodelist1.item(0).getTextContent();
			String result = pc.decrypt(encrypt);
			log.info("receive msg from wx server : "+result);


		} catch (Exception e) {
			log.error("failed to process message from wx server !", e);
		}
		return "";
	}
	
	
	/**
	 * 接收绑定请求
	 * @param request
	 * @param carNum
	 * @param mobileNum
	 * @param openID
	 * @return
	 */
	@RequestMapping(value = "/car_binding", headers = {}, method = { RequestMethod.POST })
	@ResponseBody
	public String binding(HttpServletRequest request, String carNum, String mobileNum, String openID) {

		System.out.println("car : "+carNum);
		System.out.println("mobile : "+mobileNum);
		System.out.println("user : "+openID);
		
		WxCar c = new WxCar(openID, mobileNum, carNum);
		
		if(!WxStore.contains(c)){
			WxStore.save(c);
			return "操作成功！";
		}else{
			return "操作失败！已存在的绑定信息！";
		}
	}
	
	
	/**
	 * 接收生成二维码请求
	 * @param request
	 * @param carNum
	 * @param mobileNum
	 * @param openID
	 * @return
	 */
	@RequestMapping(value = "/car_qrcode", headers = {}, method = { RequestMethod.POST })
	@ResponseBody
	public WxQRcode qrcode(HttpServletRequest request, String carNum, String mobileNum, String openID) {

		WxCar c = new WxCar(openID, mobileNum, carNum);
		
		if(!WxStore.contains(c)){
			return null;
		}
		
//		String key = "{\"car\":"+carNum+",\"mobile\":"+mobileNum+",\"user\":"+openID+"}";
		
		String url = "http://www.15tech.com.cn/wx";
//		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx1409ecc83563ac86&redirect_uri=http%3A%2F%2Fwww.15tech.com.cn%2Fwx&response_type=code&scope=snsapi_base#wechat_redirect";
//		try {
//			url = URLEncoder.encode(url, "UTF-8");
//		} catch (UnsupportedEncodingException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
		WxQRcode qr = WxSender.generateQRcode(url);
		
		return qr;
	}
	
	@RequestMapping(value = "/test_enrollment", headers = {}, method = { RequestMethod.POST })
	@ResponseBody
	public String testEnrollment(HttpServletRequest request, String openid) {
		
		log.info("发送消息给openid："+(openid=(Tool.isEmpty(openid)?SysConfig.get(PropKey.TEST_OPENID):openid)));
		
		WxMessage wm = new WxMessage();
		wm.setMsgContent("您好！这是一个转正提醒的测试消息！");
		wm.setOpenId(openid);
		wm.setEnrollmentTime(new Date());
		WxSender.enrollment(wm);

		return "";
	}
	
	
}
